//
//  URLRequest.m
//  Hangxin
//
//  Created by wang fengquan on 7/2/11.
//  Copyright 2011 company. All rights reserved.
//

#import "URLRequest.h"
@interface URLRequest(private)
-(NSData*) buildMultipartFormDataPostBodyWithboundary:(NSString*)boundary fileds:(NSMutableDictionary *)fieldParams  andFile:(NSMutableDictionary *)fileparam;
@end

@implementation URLRequest

- (id)initWithURL:(NSString *)urlString andDelegate:(id<IRequest>)urlDelegate
{
	self = [super init];
	if (self)
	{
		self.delegate = urlDelegate;
         self.connection = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60] delegate:self];
		self.responseData = [[NSMutableData alloc] init];
		
	}
	
	return self;
}


- (id)initWithURL:(NSString *)urlString httpMethod:(NSString *)method body:(NSString *)body andDelegate:(id<IRequest>)urlDelegate{
	self = [super init];
	if (self){
		self.delegate = urlDelegate;
		NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
		[request setHTTPMethod:method];
		if(body != nil)
			[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
		
		self.connection = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]
													  delegate:self];
		self.responseData = [[NSMutableData alloc] init];
	}
	
	return self;
}		 


//采用post方法来发送数据;数据格式如：mobile=%@&password=%@
-(id)initWithPostURL:(NSString *)urlString andDelegate:(id <IRequest>)urlDelegate andPostData:(NSMutableDictionary *)params andFile:(NSMutableDictionary *)fileDictory{
	self = [super init];
	if (self) {
        NSString  *boundary =  @"0xKhTmLbOuNdArYckkk" ;
        NSURL  *BaseUrl = [ NSURL   URLWithString :urlString];
        NSMutableURLRequest  *mainRequest =[NSMutableURLRequest requestWithURL:BaseUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        [mainRequest  setHTTPMethod : @"POST" ];
        NSString  *contentType = [ NSString   stringWithFormat : @"multipart/form-data; boundary=%@" , boundary,  nil ];
        [mainRequest  setValue :contentType  forHTTPHeaderField : @"Content-Type" ];
        NSData *postBody=[self buildMultipartFormDataPostBodyWithboundary:boundary fileds:params andFile:fileDictory];
        [mainRequest  setHTTPBody :postBody];
		self.delegate = urlDelegate;
		self.connection = [[NSURLConnection alloc] initWithRequest:mainRequest delegate:self];
		self.responseData = [[NSMutableData alloc] init];
	}
	
	return self;

}

-(id)postWithUrl:(NSString*)url fileds:(NSMutableDictionary *)fieldParams  andFile:(NSMutableDictionary *)fileparam{
    NSString  *boundary =  @"0xKhTmLbOuNdArYckkk" ;
    NSURL  *BaseUrl = [ NSURL   URLWithString :url];
    NSMutableURLRequest  *mainRequest =[NSMutableURLRequest requestWithURL:BaseUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [mainRequest  setHTTPMethod : @"POST" ];
    NSString  *contentType = [ NSString   stringWithFormat : @"multipart/form-data; boundary=%@" , boundary,  nil ];
    [mainRequest  setValue :contentType  forHTTPHeaderField : @"Content-Type" ];
    NSData *postBody=[self buildMultipartFormDataPostBodyWithboundary:boundary fileds:fieldParams andFile:fileparam];
    [mainRequest  setHTTPBody :postBody];
    NSURLResponse  *shareResponse;
    NSError  *error;
    NSData  *responseData = [ NSURLConnection   sendSynchronousRequest :mainRequest  returningResponse:&shareResponse  error :&error];
    NSHTTPURLResponse  *httpResponse = ( NSHTTPURLResponse  *)shareResponse;
    int  statusCode = [httpResponse  statusCode];
    if  (statusCode ==  200 ) {
        NSError *jsonError;
        id result=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&jsonError];
        if (jsonError.code==0) {
            return result;
        }else{
            NSLog ( @"json解析 error code=%d,desc = %@" ,error.code,error.localizedDescription);
            return @{@"code":@"-100",@"message":@"服务器数据异常"};
        }
        
    }else{
        // NSLog ( @"status code =%d,allHeaderFields = %@",statusCode ,httpResponse.allHeaderFields);
        return @{@"code":@"101",@"message":@"网路异常"};
    }
    
    
}


- (void)cancelConnection{
	_delegate = nil;
	[_connection cancel];
}

- (void)startLoadData{
	if (_connection)
	{
		[_connection start];
	}
}



#pragma mark -
#pragma mark NSURLConnection
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
	//NSLog(@"did receive data");
	[_responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
	[self.responseData appendData:0x0];
    NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
	[_delegate requestFinished:responseString];
	
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
	/*
	NSMutableData *data = [[NSMutableData alloc] init];
	_responseData = data;
	[data release];
	[receiveData setLength:0];
	 */
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	//NSLog(@"did failed");
	//NSLog([error localizedDescription]);
	
	[_delegate requestFailed:_responseData error:error.localizedDescription];
}

-(NSData*) buildMultipartFormDataPostBodyWithboundary:(NSString*)boundary fileds:(NSMutableDictionary *)fieldParams  andFile:(NSMutableDictionary *)fileparam{
    
    NSString  *bodyPrefixString = [ NSString   stringWithFormat : @"--%@\r\n" , boundary];
    NSString  *bodySuffixString = [ NSString   stringWithFormat : @"--%@--\r\n" , boundary];
    NSMutableData  *postBody = [ NSMutableData   data];
    
    //传普通字符串
    if (fieldParams!=nil) {
        NSArray *fieldKeys=[fieldParams allKeys];
        for (int i=0; i<[fieldKeys count]; i++) {
            id values=[fieldParams objectForKey:[fieldKeys objectAtIndex:i]];
            if (values!=nil) {
                [postBody  appendData :[bodyPrefixString  dataUsingEncoding : NSUTF8StringEncoding  allowLossyConversion : NO ]];
                NSString  *bodyUpdateField = [ NSString   stringWithFormat : @"Content-Disposition: form-data;name=\"%@\"\r\n\r\n%@\r\n" ,[fieldKeys objectAtIndex:i] ,values];
                [postBody  appendData :[bodyUpdateField  dataUsingEncoding : NSUTF8StringEncoding]];
            }
        }
    }
    
    
    //传图片或者文件
    if (fileparam!=nil) {
    [postBody appendData:[self  generateFormDataFromPostDictionary:fileparam boundary:boundary]];
    
    }
    //结束标示
    [postBody  appendData :[bodySuffixString  dataUsingEncoding : NSUTF8StringEncoding  allowLossyConversion : NO ]];
    return postBody;
}

//创建postdata
- (NSData*)generateFormDataFromPostDictionary:(NSDictionary*)dict boundary:(NSString*)boundary{
    NSMutableData* result = [NSMutableData data];
    NSArray* keys = [dict allKeys];
     for (int i = 0; i < [keys count]; i++){
        id value = [dict valueForKey: [keys objectAtIndex:i]];
        [result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        if ([value isKindOfClass:[NSData class]]){
            NSString  *imageData = [NSString   stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",[[keys objectAtIndex:i] stringByDeletingPathExtension],[keys objectAtIndex:i]];
            [result appendData:[imageData  dataUsingEncoding : NSUTF8StringEncoding]];
            //声明上传文件的格式
           /* MP4 视频 	video/mp4
            MP3 音频 	audio/mpeg
            JPEG 图片 	image/jpeg
            GIF 图片 	image/gif
            PNG 图片 	image/png
            */
            if ([[keys objectAtIndex:i] hasPrefix:@"mp3"]) {
                NSString *contenttype=[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n",@"audio/mpeg"];
                [result appendData:[contenttype  dataUsingEncoding : NSUTF8StringEncoding]];
            }else{
                NSString *contenttype=[NSString stringWithFormat:@"Content-Type: image/%@\r\n\r\n",[[keys objectAtIndex:i] pathExtension]];
               [result appendData:[contenttype  dataUsingEncoding : NSUTF8StringEncoding]];
            }
            
            [result appendData:[dict objectForKey:[keys objectAtIndex:i]]];
            [result appendData:[@"\r\n"  dataUsingEncoding : NSUTF8StringEncoding]];
        }
        else{
            // all non-image fields assumed to be strings
            NSString *formstring = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", [keys objectAtIndex:i]];
             [result appendData:[formstring  dataUsingEncoding : NSUTF8StringEncoding]];
            [result appendData:[@"\r\n"  dataUsingEncoding : NSUTF8StringEncoding]];
        }
    } 

    return result; 
}

@end
